﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.Script.Serialization;
using System.Web.UI.WebControls;

public partial class Collection : System.Web.UI.Page, ICallbackEventHandler
{
    Dictionary<string, string> ClientRequest = null;
    Dictionary<string, string> ClientResponse = null;
    JavaScriptSerializer serializer;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsCallback)
        {
            CallBackReference();
            if (!IsPostBack)
            {
                if (SessionInfo.prop_getObj.EmployeeID == 0)
                    Response.Redirect("login.aspx");
                else
                {
                    hdnExportToExcelFilePath.Value = GlobalDefaultValues.DHTMLXExportToExcelFilePath;
                    PLMstFormMasters objRights = CommonUtil.CheckRightsForForm("2");
                    if (objRights.ViewAccess == false)
                        Response.Redirect("Login.aspx");
                    if (Request.Params.Count > 0 && Request.Params[0] == "Excel")
                    {
                        UI_ExportToExcel();
                    }

                    cboCompany.Focus();
                    UI_Filldropdowns();
                    SessionInfo.prop_getObj.CollectionEntrySearchCriteria = new PLCollection();
                    grdResult.DataSource = new BL_Collection().BL_GetCollectionTractions(new PLCollection());
                    grdResult.DataBind();
                }
            }
        }
    }

    protected void UI_Filldropdowns()
    {
        List<PLCompany> objCompanies = new BL_Company().BL_fnGetCompanyNameList(new PLCompany() { SearchIsActive = true });
        CommonUtil.LoadDropdown(cboCompany, objCompanies, "CompanyID", "Name");

        List<PLClient> objClients = new BL_Client().BL_fnGetClientNameList(new PLClient() { SearchIsActive = true });
        CommonUtil.LoadDropdown(cboClient, objClients, "ClientID", "ClientName");
        //CommonUtil.LoadDropdown(cboAddClient, objClients, "ClientID", "ClientName", "[Select Client]");

        List<PLContract> objContracts = new BL_Contract().BL_fnGetContractNameList(new PLContract() { SearchIsActive = true });
        CommonUtil.LoadDropdown(cboContract, objContracts, "ContractID", "ContractName");
        //CommonUtil.LoadDropdown(cboAddContract, objContracts, "ContractID", "ContractName", "[Select Contract]");

        List<PLPaymentMode> objPaymentMode = new BL_PaymentMode().BL_fnGetPaymentModeNameList(new PLPaymentMode() { SearchIsActive = true });
        CommonUtil.LoadDropdown(cboPaymentMode, objPaymentMode, "PaymentModeID", "PaymentModeName");
    }

    // Override the Render method to ensure that this control
    // is nested in an HtmlForm server control, between a <form runat=server>
    // opening tag and a </form> closing tag.
    protected override void Render(HtmlTextWriter writer)
    {
        // Ensure that the control is nested in a server form.
        if (Page != null)
        {
            Page.VerifyRenderingInServerForm(this);
        }
        base.Render(writer);
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        /* Verifies that the control is rendered */
    }

    protected void UI_ExportToExcel()
    {
        if (SessionInfo.prop_getObj.CollectionEntrySearchCriteria != null)
        {
            SessionInfo.prop_getObj.CollectionEntrySearchCriteria = new PLCollection();
            grdResult.DataSource = new BL_Collection().BL_GetCollectionTractions(new PLCollection());

            List<PLCollection> objCollection = new BL_Collection().BL_GetCollectionTractions(SessionInfo.prop_getObj.CollectionEntrySearchCriteria);
            int intIncrementer = 0;
            var varInvList = (from l in objCollection
                              select new
                              {
                                  SrNo = intIncrementer++,
                                  CompanyName = l.CompanyName,
                                  ClientName = l.ClientName,
                                  ContractName = l.ContractName,
                                  InvoiceNo = l.InvoiceNo,
                                  CollectionNo = l.CollectionNo,
                                  CollectionDate = l.CollectionDate.ToString("dd/MM/yyyy"),
                                  CollectionType = l.CollectionType,
                                  DrawnOnBank = l.DrawnOnBank,
                                  CollectionRefNo = l.CollectionRefNo,
                                  Amount = l.Amount,
                                  TDSAmount = l.TDSAmount,
                                  GrossAmount = l.GrossAmount
                              });
            List<string> lstHeader = new List<string>() { "Sr.", "Company", "Client", "Contract", "Invoice #", "Collection #", "Collection Date", "Collection Type", "Drawn Bank", "Ref. No.", "Amount", "TDS Amount", "Gross Amount" };
            CommonUtil.ExportToExcelWithEPPlus(lstHeader, varInvList, Response, "Collection List");
        }
        else
        {
            Response.End();
        }
    }

    #region callback functions
    public void CallBackReference()
    {
        string strReference = Page.ClientScript.GetCallbackEventReference(this, "args", "getResponse", "context", "ClientCallbackError", true);
        string strScript = " function UseCallback(args,context) { " + strReference + " ; } ";
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "UseCallback", strScript, true);
    }

    public string GetCallbackResult()
    {
        System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        oSerializer.MaxJsonLength = GlobalDefaultValues.MaxJsonLength;
        return oSerializer.Serialize(ClientResponse);
    }

    public void RaiseCallbackEvent(string strEventArgument)
    {
        try
        {
            serializer = new JavaScriptSerializer();
            ClientRequest = serializer.Deserialize<Dictionary<string, string>>(strEventArgument);
            ClientResponse = new Dictionary<string, string>();
            string Track = ClientRequest["Track"];
            ClientResponse = new Dictionary<string, string>();
            ClientResponse["Track"] = Track;
            if (SessionInfo.prop_getObj.EmployeeID == 0)
            {
                ClientResponse["SessionTimeOut"] = "1";
            }
            else
            {
                ClientResponse["SessionTimeOut"] = "0";
                if (Track.Equals("GetSearchResult"))
                {
                    UI_SearchResult();
                }
                if (Track.Equals("EdiRecord"))
                {
                    UI_EditRecord();
                }
                else if (Track.Equals("AddRecord"))
                {
                    UI_AddRecord();
                }
                else if (Track.Equals("DeleteRecord"))
                {
                    UI_DeleteRecord();
                }
                else if (Track.Equals("InsertEditDetails"))
                {
                    PLCollection objCollection = new PLCollection();

                    objCollection.CollectionID = TrynParse.parseInt(ClientRequest["CollectionID"]);
                    objCollection.InvoiceID = TrynParse.parseInt(ClientRequest["InvoiceID"]);
                    objCollection.InvoiceNo = TrynParse.parseString(ClientRequest[txtAddInvoiceNo.ID]);

                    objCollection.InvoiceNo = TrynParse.parseString(ClientRequest[txtAddInvoiceNo.ID]);
                    objCollection.CollectionDate = CommonUtil.fnGetDateFromJSFile(ClientRequest[txtAddCollectionDate.ID]).Value;

                    objCollection.CollectionType = TrynParse.parseString(ClientRequest[cboAddCollectionType.ID]);
                    objCollection.DrawnOnBank = TrynParse.parseString(ClientRequest[txtAddDrawnOnBank.ID]);
                    objCollection.CollectionRefNo = TrynParse.parseString(ClientRequest[txtAddRefNo.ID]);
                    objCollection.Amount = TrynParse.parseDecimal(ClientRequest[txtAddAmount.ID]);
                    objCollection.TDSAmount = TrynParse.parseDecimal(ClientRequest[txtAddTDSAmount.ID]); 

                    objCollection.InvoiceNo = TrynParse.parseString(ClientRequest[txtAddInvoiceNo.ID]);
                    objCollection.IsTDSDeducted = (TrynParse.parseString(ClientRequest["TDSDeducted"]) == "1" ? true : false);


                    try
                    {
                        int Result = new BL_Collection().BL_InsertUpdateCollections(objCollection);
                        if (Result > 0)
                        {
                            ClientResponse["strSaveMessage"] = GlobalDefaultValues.SaveMessage.Replace("XXX", "Collection");
                            ClientResponse["strUpdateMessage"] = GlobalDefaultValues.UpdateMessage.Replace("XXX", "Collection");
                            ClientResponse["IsSuccess"] = "1";
                            UI_SearchResult();
                        }
                        else
                        {
                            ClientResponse["strMessage"] = GlobalDefaultValues.SaveErrorMessage.Replace("XXX", "Collection");
                            ClientResponse["IsSuccess"] = "0";
                        }
                    }
                    catch (Exception ex)
                    {
                        ClientResponse["strMessage"] = ex.Message;
                        CommonUtil.Elmah_SignalException(ex, this.Context, "Collection - Method: RaiseCallbackEvent(), Track-InsertEditDetails");
                        ClientResponse["IsSuccess"] = "0";
                    }
                }
            }
        }
        catch (Exception ex)
        {
            CommonUtil.Elmah_SignalException(ex, this.Context, "Invoice - Method: RaiseCallbackEvent()");
        }
    }


    private void UI_SearchResult()
    {
        PLCollection objCollection = new PLCollection();
        objCollection.SearchCompanyIDs = ClientRequest[cboCompany.ID];
        objCollection.SearchClientIDs = ClientRequest[cboClient.ID];
        objCollection.SearchContractIDs = ClientRequest[cboContract.ID];
        objCollection.SearchPaymentModeIDs = ClientRequest[cboPaymentMode.ID];
        objCollection.SearchInvoiceNo = ClientRequest[txtInvoiceNo.ID];
        objCollection.SearchContractNo = ClientRequest[txtContractNo.ID];

        objCollection.SearchInvoiceStartDate = CommonUtil.fnGetDateFromJSFile(ClientRequest[txtInvoiceStartDate.ID]);
        objCollection.SearchInvoiceEndDate = CommonUtil.fnGetDateFromJSFile(ClientRequest[txtInvoiceEndDate.ID]);
        objCollection.SearchCollectionStartDate = CommonUtil.fnGetDateFromJSFile(ClientRequest[txtInvoiceStartDate.ID]);
        objCollection.SearchCollectionEndDate = CommonUtil.fnGetDateFromJSFile(ClientRequest[txtInvoiceEndDate.ID]);

        grdResult.DataSource = new BL_Collection().BL_GetCollectionTractions(objCollection);
        grdResult.DataBind();
        ClientResponse["grdResult"] = CommonUtil.GetRenderControl(grdResult);
    }

    private void UI_EditRecord()
    {
        //int intInvoiceID = TrynParse.parseInt(ClientRequest[hdnInvoiceID.ID]);
        //PLInvoice objInvoice = new BL_Invoice().BL_fnGetSingleInvoiceTransactions(new PLInvoice() { TrnInvoiceID = intInvoiceID });
        //List<PLClient> objClients = new BL_Client().BL_fnGetClientNameList(new PLClient() { SearchIsActive = true, AddClientID = objInvoice .ClientID});
        //CommonUtil.LoadDropdown(cboAddClient, objClients, "ClientID", "ClientName");

        //List<PLContract> objContracts = new BL_Contract().BL_fnGetContractNameList(new PLContract() { SearchIsActive = true, AddContractID = objInvoice .ContractID});
        //CommonUtil.LoadDropdown(cboAddContract, objContracts, "ContractID", "ContractName");

        //List<PLContract> objTrnContract = new BL_Invoice().BL_GetTrnContract(new PLContract() { SearchIsActive = true, ClientID = objInvoice.ClientID, CompanyID = objInvoice.CompanyID, ContractID = objInvoice.ContractID });
        //CommonUtil.LoadDropdown(cboAddTrnContract, objTrnContract, "TrnContractID", "ContractNo");


        //PLContract objContractList = new BL_Invoice().BL_GetPendingTrnContractsDetails(new PLContract() { TrnContractID = objInvoice.TrnContractID });
        //ClientResponse[txtAddContractPer.ID] = objContractList.PaymentLevelPer.Value.ToString();
        //ClientResponse[lblContractAmount.ID] = objContractList.ContractAmount.Value.ToString();
        //ClientResponse["IsLastPaymentMode"] = objContractList.IsLastPaymentMode.GetValueOrDefault().ToString(); 


        //ClientResponse["cboAddClient"] = CommonUtil.GetRenderControl(cboAddClient);
        //ClientResponse["cboAddContract"] = CommonUtil.GetRenderControl(cboAddContract);
        //ClientResponse["cboAddTrnContract"] = CommonUtil.GetRenderControl(cboAddTrnContract);
        //ClientResponse["RowID"] = ClientRequest["RowID"];

    }

    private void UI_AddRecord()
    {
        string strInvoiceNo = TrynParse.parseString(ClientRequest[txtAddInvoiceNo.ID]);
        string strFlag = TrynParse.parseString(ClientRequest["Flag"]);
        PLCollection plColl = new BL_Collection().BL_GetInvoiceDetail(new PLCollection() { InvoiceNo = strInvoiceNo });
        if (plColl == null)
        {
            ClientResponse["Flag"] = "1";
        }
        else if ((plColl.IsCollectionReceived ?? false) == true && strFlag == "Add")
        {
            ClientResponse["Flag"] = "2";
        }
        else
        {
            ClientResponse["Flag"] = "3";
            ClientResponse[hdnInvoiceID.ID] = plColl.InvoiceID.Value.ToString();
            ClientResponse[lblAddCompany.ID] = plColl.CompanyName;
            ClientResponse[lblAddClient.ID] = plColl.ClientName;
            ClientResponse[lblAddContract.ID] = plColl.ContractName;
            ClientResponse[lblAddPaymentMode.ID] = plColl.PaymentModeName;
            ClientResponse[lblPaymentLevel.ID] = plColl.PaymentLevelName;
            ClientResponse[txtAddAmount.ID] = plColl.Amount.Value.ToString("#0");
            if (ClientRequest.ContainsKey("RowID") == true)
                ClientResponse["RowID"] = ClientRequest["RowID"];
        }
    }

    private void UI_DeleteRecord()
    {
        int intCollectionID = TrynParse.parseInt(ClientRequest["CollectionID"]);

        try
        {
            int Result = new BL_Collection().BL_DeleteCollections(new PLCollection() { CollectionID = intCollectionID });
            if (Result > 0)
            {
                ClientResponse["strMessage"] = GlobalDefaultValues.DeleteMessage.Replace("XXX", "Collection");
                ClientResponse["IsSuccess"] = "1";
                UI_SearchResult();
            }
            else
            {
                ClientResponse["strMessage"] = GlobalDefaultValues.SaveErrorMessage.Replace("XXX", "Collection");
                ClientResponse["IsSuccess"] = "0";
            }
        }
        catch (Exception ex)
        {
            ClientResponse["strMessage"] = ex.Message;
            CommonUtil.Elmah_SignalException(ex, this.Context, "Collection - Method: RaiseCallbackEvent(), Track-DeleteRecord");
            ClientResponse["IsSuccess"] = "0";
        }
    }

    protected void grdResult_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[0].Style["display"] = "none";
            e.Row.Cells[1].Style["display"] = "none";
            e.Row.Cells[2].Style["display"] = "none";
            e.Row.Cells[3].Text = (e.Row.RowIndex + 1).ToString();
        }
        else if (e.Row.RowType == DataControlRowType.Header)
        {
            e.Row.Cells[0].Style["display"] = "none";
            e.Row.Cells[1].Style["display"] = "none";
            e.Row.Cells[2].Style["display"] = "none";
        }
    }
    #endregion

}